<template>
  <div class="drugStorage">
    <div class="drugStorage-page">
      <div class="drugStorage-page-content">
        <div class="drugStorage-page-form">
          <el-input
            style="width: 300px"
            placeholder="请输入内容"
            v-model="filterText"
            clearable
            @clear="onSeacher"
          >
            <template #suffix>
              <el-icon class="suffix-search" @click="onSeacher">
                <Search />
              </el-icon>
            </template>
          </el-input>

          <div class="drugStorage-page-form-right">
            <el-button
              type="primary"
              @click="onClick"
              v-btnPermission="'bnt-dept-add'"
              >+ 新增</el-button
            >
          </div>
        </div>
        <div class="drugStorage-page-table">
          <Table
            :columns="tableColumns"
            :loading="loading"
            :data-source="dataSource"
          />
        </div>
        <div class="drugStorage-page-pagination">
          <Pagination
            :count="total"
            :page-size="pageSize"
            :pageNo="currentPage"
            @onPagechange="handlePageChange"
            @onSizechange="handleSizeChange"
          />
        </div>
        <updata ref="updataRef" :data-type="dataType" @refresh="onRefresh" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue';
import { ElForm } from 'element-plus';
import store from '@/store';
import updata from './common/updata.vue';
import type { TableColumn } from '@/types/table';
import type { FormStorage, List } from '@/types/storage/index';
import type { FormInstance, FormRules } from 'element-plus';
import type { Action } from 'element-plus';
import {
  getClinicDeptList,
  deleteClinicDept,
  disableDept,
  enableDept,
} from '@/api/clinic/index';
import stores from '@/store';
const userBaseStore = stores.useBaseDataStore();
definePageMeta({
  name: '科室管理',
});
const dataSource = ref<any[]>([]); // 数据源
const total = ref(0); // 总条数
const currentPage = ref(1); // 当前页
const pageSize = ref(10); // 每页条数
const dataType = ref(1); // 数据类型
const filterText = ref('');
const loading = ref(false);
const updataRef = ref<InstanceType<typeof updata>>();
const tableColumns: TableColumn[] = [
  { prop: 'deptName', label: '科室名', width: 120 },
  // {
  //   prop: 'directorName',
  //   label: '负责人名',
  //   width: 100,
  // },
  {
    prop: 'empNo',
    label: '工号',
  },
  { prop: 'directorName', label: '负责人' },
  {
    prop: 'isEnabledName',
    label: '启用状态',
    type: 'tag',
    componentProps: {
      formatter: (row) => {
        row.isEnabledName = row.isEnabled === '1' ? '启用' : '停用';
        return row.isEnabledName;
      },
    },
  },
  {
    prop: 'action',
    label: '操作',
    type: 'action',
    width: 170,
    componentProps: {
      fixed: 'right',
    },
    buttonGroup: [
      {
        label: '编辑',
        permissions: 'btn-dept-edit',
        type: 'text',
        click: (row: any) => {
          updataRef.value?.open1(row);
          dataType.value = 1; // 设置数据类型为编辑
        },
      },
      {
        label: '启用',
        statusName: ['isEnabledName'],
        permissions: 'btn-dept-enable',
        status: '停用',
        type: 'text',
        click: (row: any) => {
          enableDept({ deptId: row.deptId }).then((res) => {
            onRefresh(); // 刷新列表
            if(res.code == '200'){
               ElMessage({
                type: 'success',
                message: '操作成功',
                duration: 2000,
              });
            }else{
              // ElMessage({
              //   type: 'warning',
              //   message: res.msg,
              //   duration: 2000,
              // });
            }
           
          });
        },
      },
      {
        label: '停用',
        statusName: ['isEnabledName'],
        status: '启用',
        permissions: 'btn-dept-disable',
        type: 'text',
        color: '#D90000',
        click: (row: any) => {
          disableDept({ deptId: row.deptId }).then((res) => {
            onRefresh(); // 刷新列表
            if(res.code == '200'){
              ElMessage({
                type: 'success',
                message: '操作成功',
                duration: 2000,
              });
            }else{
              // ElMessage({
              //   type: 'warning',
              //   message: res.msg,
              //   duration: 2000,
              // });
            }
          });
        },
      },
      {
        label: '删除',
        type: 'text',
        permissions: 'btn-dept-del',
        color: '#D90000',
        click: (row: any) => {
          ElMessageBox.alert('确定要删除吗？', {
            confirmButtonText: '确定',
            callback: (action: Action) => {
              if(action == 'cancel'){
                  return;
              }
              try {
                deleteClinicDept({ deptId: row.deptId }).then((res) => {
                  if (res.code == '200') {
                    ElMessage({
                      type: 'success',
                      message: '删除成功',
                    });
                    getClinicDeptData();
                  } else {
                    // ElMessage({
                    //   type: 'error',
                    //   message: res.msg || '删除失败',
                    // });
                  }
                });
              } catch (error: any) {
                //console.log(error, '删除失败');
              }
            },
          });
        },
      },
    ],
  },
];

//弹窗调用
interface DialogRefType {
  open: () => void;
  handleClose: () => void;
}
const dialogRef = ref<DialogRefType | null>(null);
const title = ref<string>('');
const handlePageChange = (page: number) => {
  //console.log('当前页:', page);
  currentPage.value = page;
  getClinicDeptData();
};
const onClick = () => {
  dataType.value = 0; // 设置数据类型为新增
  updataRef.value?.open();
};
const handleSizeChange = (size: number) => {
  //console.log('每页条数:', size);
  currentPage.value = 1;
  pageSize.value = size;
  getClinicDeptData();
};
const handleClose = (e: string) => {
  //console.log(e, '父组件方法被调用');
};
const onRefresh = () => {
  getClinicDeptData();
  userBaseStore.fetchDeptSelectList();
};
const getClinicDeptData = async () => {
  try {
    const params = {
      deptName: filterText.value,
      pageNo: currentPage.value,
      pageSize: pageSize.value,
    };
    loading.value = true;
    const res = await getClinicDeptList(params);
    if (res.code === '200') {
      dataSource.value = res.data.list || [];
      total.value = res.data.totalCount; // 假设返回的数据长度即为总条数
    } else {
      //ElMessage.error('获取科室列表失败');
    }
    loading.value = false;
  } catch (error) {
    //console.error('获取科室数据失败:', error);
    //ElMessage.error('获取科室数据失败，请稍后重试');
    loading.value = false;
  }
};
const onSeacher = () => {
  currentPage.value = 1;
  getClinicDeptData();
};
onMounted(() => {
  // 获取科室列表
  getClinicDeptData();
});
</script>

<style lang="scss" scoped>
.drugStorage {
  height: 100%;
}
.drugStorage-dialog {
  width: 80%;
  margin: 0 auto;
}
.drugStorage-page {
  background: #fff;
  border-radius: 6px;
  height: 100%;
  .drugStorage-page-nav {
    display: flex;
    align-items: center;
    justify-content: left;
    border-radius: 4px;
    border-bottom: 1px solid #e7e7e7;
    .el-dropdown-link {
      background: rgba(22, 173, 164, 0.08);
      border-radius: 0px 0px 0px 0px;
      padding: 16px 21px;
      cursor: pointer;
      color: var(--el-color-primary) !important;
      display: flex;
      font-size: 16px;
      align-items: center;
    }
  }
  .drugStorage-page-content {
    padding: 10px 24px;
    height: calc(100% - 65px);
    .drugStorage-page-form {
      display: flex;
      align-items: center;
      .drugStorage-page-form-right {
        margin-left: auto;
      }
    }
    .drugStorage-page-table {
      margin-top: 22px;
      height: calc(100% - 68px);
    }
    .drugStorage-page-pagination {
      margin-top: 24px;
      display: flex;
      align-items: center;
      .drugStorage-page-pagination-total {
        margin-right: auto;
        font-family: Microsoft YaHei, Microsoft YaHei;
        font-weight: 400;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.6);
        text-align: left;
        font-style: normal;
        text-transform: none;
      }
    }
  }
}
</style>
